package vn.fpt.fsoft.dao;

import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import vn.fpt.fsoft.util.*;
import vn.fpt.fsoft.entity.Country;


/*
 * Class CountryDAO
 *
 * Version 1.0
 *
 * 22-August-2014
 *
 * Modification Logs:
 * DATE					AUTHOR				DESCRIPTION
 * ------------------------------------------------------------
 * 22-August-2014		XuanTuan 			Create CountryDAO
 */
public class CountryDAO {
    private SessionFactory sessionFactory;
    private Session session;
    private Transaction transaction;
    
    /**
     * Constructor
     */
    public CountryDAO() {
        this.sessionFactory = HibernateUtil.getSessionFactory();
        this.session = null;
        this.transaction = null;
    }
    
    /**
     * @return list all country
     */
    @SuppressWarnings("unchecked")
    public List<Country> getAllCountry() {
        session = sessionFactory.openSession();
        List<Country> list = null;
        
        try {
            transaction = session.beginTransaction();
            list = session.createCriteria(Country.class).list();
            transaction.commit();
        } catch (HibernateException e) {
            if (transaction == null)
                transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return list;
    }
    
    public boolean addCountry(Country country) {
        session = sessionFactory.openSession();

        try {
            transaction = session.beginTransaction();
            session.save(country);
            transaction.commit();
            return true;
        } catch (HibernateException e) {
            if (transaction == null)
                transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return false;
    }
}
